<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElScrollbar, ElInput } from 'element-plus'
import VoiceInput from './VoiceInput/index.vue'
import { useChatStore } from '@/stores/chat'
import { useUserStore } from '@/stores/user'

const chatStore = useChatStore()
const userStore = useUserStore()
const props = defineProps({
  client: {
    type: Object,
    required: true
  },
  type: {
    type: String,
    required: true
  }
})
const emit = defineEmits(['toast', 'onTts'])

const messageList = ref([])
const scrollbarRef = ref(null)

const scrollToBottom = () => {
  nextTick(() => {
    scrollbarRef.value?.setScrollTop(9999)
  })
}

onMounted(() => {
  props.client.on('message', (topic, message) => {
    try {
      const data = JSON.parse(message.toString())
      if (props.type === 'battary' && topic === 'poc/agent/vehicle/battery/test_device1') {
        messageList.value.push({
          type: 'agent',
          content: data.message  
        })
        emit('onTts', data.message)
      } else if (props.type === 'box' && topic === 'poc/agent/chat/response/web_device1' && data.user_id === userStore.token && data.type === 2) {
        let message = data.reason
        if (typeof message === 'object'){
          message = message.join(', ')
        }
        messageList.value.push({
          type: 'agent',
          content: message
        })
        emit('onTts', message)
        if (data.commands?.length) {
          emit('toast', data.commands)
        }
      } else if (props.type === 'home' && topic === 'poc/agent/chat/response/web_device1' && data.user_id === userStore.token && data.type === 3) {
        let message = data.message
        if (typeof message === 'object'){
          message = message.join(', ')
        }
        messageList.value.push({
          type: 'agent',
          content: message
        })
        emit('onTts', message)
        if (data.commands?.length) {
          emit('toast', data.commands)
        }
      } else if (props.type === 'phone' && topic === 'poc/agent/chat/phone/response/web_device1') {
        let message = data.message
        messageList.value.push({
          type: 'agent',
          content: message
        })
        emit('onTts', message)
      } else if (props.type === 'ac' && topic === 'poc/agent/chat/ac/response/web_device1' && data.user_id === userStore.token) {
        let message = data.reason
        if (data.suggested_question){
          let newQurstion = JSON.parse(data.suggested_question)
          if (newQurstion?.question){
            message = newQurstion.question
          }
        }
        messageList.value.push({
          type: 'agent',
          content: message
        })
        emit('onTts', message)
        if (data.commands?.length) {
          emit('toast', data.commands)
        }
      } else if(props.type === 'ac' && topic === 'poc/agent/chat/ac/event/test_device1') {
        let message = data.reason
        messageList.value.push({
          type: 'agent',
          content: message
        })
        emit('onTts', message)
        if (data.commands?.length) {
          emit('toast', data.commands)
        }
      } else if (topic === 'poc/agent/vehicle/state/test_device1') {
        // 车辆状态 一句话请求需要state
        chatStore.changeCarState(data)
      } else if (props.type === 'ac' && topic === 'poc/agent/chat/ac/event/web_device1') {
        let message = data.reason
        messageList.value.push({
          type: 'agent',
          content: message
        })
        emit('onTts', message)
      }
      scrollToBottom()
    } catch (error) {
      console.error('消息解析错误:', error)
    }
  })
})

const inputContent = ref('')
const handleEnter = () => {
  if (inputContent.value.trim()) {
    const message = {
      "content": inputContent.value,
      "id": new Date().getTime(),
      "requires_confirmation": false,
      // "state": chatStore.carState,
      "tone": "贴心女友",
      user_id: userStore.token
    }
    if (props.type === 'phone') {
      message.type = 1 
      message.id = 404171775
      props.client.publish('poc/agent/chat/phone/request/web_device1', JSON.stringify(message))
    } else if (props.type === 'box') {
      message.type = 2
      message.state = chatStore.carState
      props.client.publish('poc/agent/chat/request/web_device1', JSON.stringify(message)) 
    } else if (props.type === 'home') {
      message.type = 3
      props.client.publish('poc/agent/chat/request/web_device1', JSON.stringify(message)) 
    } else if (props.type === 'ac') {
      message.type = 5
      props.client.publish('poc/agent/chat/ac/request/web_device1', JSON.stringify(message)) 
    }
    
    messageList.value.push({
      type: 'user',
      content: inputContent.value,
    })
    inputContent.value = ''
    scrollToBottom()
  }
}

const showText = (text) => {
  inputContent.value = text
}
</script>

<template>
  <div class="chat-content">
    <el-scrollbar ref="scrollbarRef">
      <div class="message-list">
        <div class="title">
          <div>Hi，欢迎使用🎉</div>
          <div class="sub" v-if="props.type === 'phone'">智能终端助手</div>
          <div class="sub" v-if="props.type === 'box'">车控助手</div>
          <div class="sub" v-if="props.type === 'home'">车家互联助手</div>
          <div class="sub" v-if="props.type === 'ac'">智能环境调节管家</div>
          <div class="sub" v-if="props.type === 'battary'">能源健康管家</div>
        </div>
        <div :class="`msg-item ${item.type} ${chatStore.showType}`" v-for="item in messageList">
          {{ item.content }}
        </div>
      </div>
    </el-scrollbar>
    <div v-if="props.type !== 'battary'" class="input-area">
      <el-input v-show="chatStore.inputWay === 'keyboard'" v-model="inputContent" class="text-input" placeholder="请输入" size="large" @keyup.enter="handleEnter"/>
      <voice-input v-show="chatStore.inputWay === 'voice'" @showText="showText" @end="handleEnter"></voice-input>
      <div :class="`change-btn ${chatStore.inputWay}`" @click="chatStore.changeInputWay"></div>
    </div>
  </div>
</template>

<style>
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  padding-top: 10px;
}

.message-list {
  padding: 10px 16px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.message-list .title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  margin-top: 30px;
}

.message-list .title .sub {
  font-size: 18px;
  font-weight: normal;
  color: #999;
  margin-top: 14px;
}

.message-list .msg-item {
  padding: 12px 16px;
  border-radius: 12px;
  margin: 8px 0;
  max-width: 70%;
  word-break: break-word;
}

.message-list .msg-item.agent {
  background-color: #e3e3e3;
  color: #333;
  align-self: flex-start;
}

.message-list .msg-item.user {
  color: #fff;
  align-self: flex-end;
  &.phone{
    background-color: #1862ef;
  }
  &.box{
    background-color: #6a18ef;
  }
  &.home{
    background-color: #F39024;
  }
  &.ac{
    background-color: #23CA3F;
  }
}

.input-area {
  padding: 14px;
  position: relative;
  .text-input {
    .el-input__wrapper{
      border-radius: 44px;
    }
  }
  .change-btn{
    position: absolute;
    right: 34px;
    top: 24px;
    width: 20px;
    height: 20px;
    cursor: pointer;
    &.keyboard{
      background-image: url('../../assets/images/voice.png');
    }
    &.voice{
      background-image: url('../../assets/images/keyboard.png');
    }
    background-size: cover; 
  }
}
</style>